<?php
/**
 * File containing the BRail_Teamware_Adapter class.
 * @package BRail_Teamware
 */

/**
 * @package BRail_Teamware
 */
class BRail_Teamware_Adapter
{
    /**
     * @var resource $_dbLink
     */
    private $_dbLink = null;

    /**
     * @param array $config
     * @throws BRail_Teamware_Exception
     */
    public function __construct(array $config)
    {
        if (!((isset($config['username'])) && (isset($config['password'])) && (isset($config['database'])))) {
            throw new BRail_Teamware_Exception(
                'Config array passed to '.__METHOD__.' misses some parameters.'
            );
        }
        if (!$this->_dbLink = @oci_connect(
            $config['username'], $config['password'], $config['database'])) {
            $error = oci_error();
            throw new BRail_Teamware_Exception(
                __METHOD__.' failed to connect to Teamware: ' . $error['message']
            );
        }
    }

    /**
     * Close Oracle connection
     */
    public function __destruct()
    {
        if (is_resource($this->_dbLink)) {
            oci_close($this->_dbLink);
        }
    }

    /**
     * Make LIKE operator case insensitive
     */
    public function makeCaseInsensitive()
    {
        oci_execute(oci_parse($this->_dbLink, 'alter session set NLS_COMP=LINGUISTIC'));
        oci_execute(oci_parse($this->_dbLink, 'alter session set NLS_SORT=BINARY_CI'));
    }

    /**
     * @param string $query
     * @return array
     */
    public function execute($query)
    {
        $results = array();
        oci_execute($stmt = oci_parse($this->_dbLink, $query));
        oci_fetch_all($stmt, $results, 0, -1, OCI_FETCHSTATEMENT_BY_ROW);
        return $results;
    }
}
